package com.yzdbx.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.SystemPropsUtil;
import com.yzdbx.task.MainTask;

import java.sql.Date;
import java.sql.Timestamp;
import java.time.LocalDate;

import java.util.ArrayList;
import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.utils
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: TODO
 * @Version: 1.0
 */
public class GenUtil {

    public static final ThreadLocal<LocalDate> CUR_DATE = new ThreadLocal<>();
    public static final ThreadLocal<Timestamp> CUR_TIME_STAMP = new ThreadLocal<>();
    public static final String IS_INIT = SystemPropsUtil.get("IS_INIT", "Y");
    public static final String CYCLE = SystemPropsUtil.get("CYCLE", "02:00:00");

    public static String getNo(Connection connection, String prefix) {
        LocalDate currentDate = CUR_DATE.get();
        if (currentDate != null) {
            String yearMonth = currentDate.toString().substring(0, 7).replace("-", "");
            String likePrefix = prefix + yearMonth;
            int maxNo = 0;
            try {
                String sql = "SELECT MAX(f4ed) FROM salesOrders WHERE f4ed LIKE ?";
                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setString(1, likePrefix + "%");
                ResultSet rs = ps.executeQuery();
                if (rs.next() && rs.getString(1) != null) {
                    String maxOrderNo = rs.getString(1);
                    // 取后三位流水号
                    maxNo = Integer.parseInt(maxOrderNo.substring(maxOrderNo.length() - 3));
                }
                rs.close();
                ps.close();
            } catch (Exception e) {
                throw new RuntimeException("生成订单号时查询数据库失败", e);
            }
            return likePrefix + String.format("%04d", maxNo + 1);
        }
        return null;
    }

    public static int getNoRepeatId(Integer id, List<Integer> existIds, List<Integer> mainIds) {
        while (existIds.contains(id)) id = RandomUtil.randomEle(mainIds);
        return id;
    }

    public static void setCurDate(LocalDate curDate) {
        CUR_DATE.set(curDate);
    }

    public static void setCurTimeStamp(Timestamp curTimeStamp) {
        CUR_TIME_STAMP.set(curTimeStamp);
    }


    public static Date ramdonDate() {
        LocalDate start = MainTask.start;
        LocalDate end = MainTask.end;
        List<LocalDate> list = new ArrayList<>();
        while (!start.isAfter(end)) {
            list.add(start);
            start = start.plusDays(1);
        }
        LocalDate localDate = RandomUtil.randomEle(list);
        return Date.valueOf(localDate);
    }

    public static String getNoFromTable(Connection connection, String prefix, String table, String field) {
        LocalDate currentDate = CUR_DATE.get();
        if (currentDate != null) {
            String ymd = currentDate.toString().replace("-", "");
            String likePrefix = prefix + ymd;
            int maxNo = 0;
            try {
                String sql = "SELECT MAX(" + field + ") FROM " + table + " WHERE " + field + " LIKE ?";
                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setString(1, likePrefix + "%");
                ResultSet rs = ps.executeQuery();
                if (rs.next() && rs.getString(1) != null) {
                    String maxOrderNo = rs.getString(1);
                    maxNo = Integer.parseInt(maxOrderNo.substring(maxOrderNo.length() - 3));
                }
                rs.close();
                ps.close();
            } catch (Exception e) {
                throw new RuntimeException("生成编号时查询数据库失败", e);
            }
            return likePrefix + String.format("%04d", maxNo + 1);
        }
        return null;
    }
}
